'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	let {
		create_date,
		name,
		shop_desc,
		shop_address,
	} = event;
	
    const collection = db.collection("shop")
    let str = 'create_date';
    const res = await collection.orderBy(str,"asc").get()  // asc 升序 , desc 降序
   
    // for(let i = 0; i < res.data.length; i++) {
    //   let d  = new Date(res.data[i].create_date);
    //   console.log("?查看日期",d, d.getFullYear(), d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes(),d.getSeconds());
    // }
    const resObj = res.data[res.data.length - 1];
    // FTT   三个字母都是测试店铺 // 省编码（GD） + 区域编号（0402） + 店铺数量（4位十六进制编码  FFFF  = 65535）
    const _shopId  =  "GD0402"; //默认广东珠海香洲区
    const res_shop_id_ary = resObj.shop_id.split(''); //拆分
    const endNum = res_shop_id_ary.length; //总长度
    if(endNum === 10) { //正常数据都是10位编码
      // 获取 最后 4 位
      var numStr = "", newNum, num16;
        for(let _i = 1; _i < 5; _i++) {
         numStr  +=  res_shop_id_ary[endNum -  (5 - _i)];
        }
      // 解析16进制 
        num16 = parseInt(numStr, 16);      // newNum = parseInt("0x" + "FFFF");
         if(num16  > 65535) {
           console.error("数量爆了", num16);
           return;
         }
      // 把数值转16进制
        newNum  = (num16 + 1).toString(16);
     
        let count = newNum.length;
        for(let _j = 0; _j < (4 - count); _j++) {
            newNum  = "0" + newNum;
        }
         newNum = _shopId + newNum.toUpperCase();
        const shop_res  = await collection.where({
           shop_id:  newNum
        }).get();
        if(shop_res.affectedDocs == 0) {
            const add_res = await collection.add({
               create_date,
               name,
               shop_desc,
               shop_address,
               shop_id: newNum
            });
            return add_res;
        }else {
             // 已存这个唯一shop id
        }
    }else {
		// 数量不匹配
	}
};